/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package services;

import dao.UserJpaController;
import entities.Institution;
import entities.User;
import java.util.List;
import vo.VOUser;

public class UserService {
    private static UserJpaController uc;
    private static InstitutionService is;
    private static UserStatsService uss;
    private static CountryService cs;


    private UserJpaController getJPAController()
    {
        if(uc == null)
            uc = new UserJpaController();
        return uc;
    }

    private InstitutionService getInstitutionService()
    {
        if(is == null)
            is = new InstitutionService();
        return is;
    }
    private CountryService getCountryService()
    {
        if(cs == null)
            cs = new CountryService();
        return cs;
    }

    private UserStatsService getStatsService()
    {
        if(uss == null)
            uss = new UserStatsService();
        return uss;
    }
    public boolean saveUser(VOUser vo)
    {
        boolean ret = true;
        uc = getJPAController();
        is = getInstitutionService();
        Institution ins = null;
        User u = new User(0, vo.getHandle(),vo.getFirstName(),vo.getLastName(),
                vo.getPassword(),vo.getEmail());
        try
        {
            ins = is.getInstitution(vo.getInstName());
            u.setInstitution(ins);
            uc.create(u);
        }
        catch (Exception e)
        {
            System.out.println("Exception at UserService.saveUser: " + e.getMessage());
            ret = false;
        }
        return ret;
    }
    public User getUser(String handle)
    {
        uc = getJPAController();
        return uc.getUserByHandle(handle);
    }
    public User getUser(int id)
    {
        uc = getJPAController();
        return uc.findUser(id);
    }

    public boolean editUser(User u)
    {
        uc = getJPAController();
        try
        {
            uc.edit(u);
            return true;
        } catch (Exception e)
        {
            return false;
        }
    }

    public boolean deleteUser(User u)
    {
        uc = getJPAController();
        uss = getStatsService();
        try
        {
            uss.deleteUserStats(uss.getStatsByUser(u));
            uc.destroy(u.getIdUser());
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

    public List<User> findUsersFromCountry(String name)
    {
        uc = getJPAController();
        cs = getCountryService();
        if(cs.getCountry(name)==null)
            return null;
        return uc.findUsersFromCountry(name);
    }

    public List<User> findUsersFromInstitution(String name)
    {
        uc = getJPAController();
        is = getInstitutionService();
        if(is.getInstitution(name)==null)
            return null;
        return uc.findUsersFromInstitution(name);
    }

}
